package com.siso.edu.instrument.util;

import android.util.Log;

import com.siso.edu.instrument.bean.RecordDataEntity;

import java.io.DataInput;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/5/9.
 */
public class FileUtil {

    private static final String TAG = "FileUtil";

    /**
     * 写入二进制数据
     */
    public static void writeBinary(RecordDataEntity entity, String path, String fileName) throws IOException {


        File f = new File(path);
        if (!f.exists()) {
            f.mkdirs();
        }
        File file = new File(path + fileName);
        if (!file.exists()) {
            file.createNewFile();
        }
        DataOutputStream out = new DataOutputStream(new FileOutputStream(path + fileName, true));
        out.writeShort(entity.getCarCode());
        out.writeByte(entity.getDeviceInfo());
        out.writeShort(entity.getYear());
        out.writeByte(entity.getMouth());
        out.writeByte(entity.getDay());
        out.writeByte(entity.getHour());
        out.writeByte(entity.getMinute());
        out.writeByte(entity.getSecond());
        out.writeShort(entity.getMiniSecond());
        out.writeDouble(entity.getLongitude());
        out.writeDouble(entity.getLatitude());
        out.writeInt(entity.getHeight());
        out.writeLong(entity.getBeginHz());
        out.writeInt(entity.getHzPoint());
        out.writeInt(entity.getStep());
        for (int i = 0; i < entity.getTestData().length; i++) {
            out.writeDouble(entity.getTestData()[i]);
        }
        if (out != null) {
            out.flush();
            out.close();
        }
        /**
         short carCode;
         byte deviceInfo;
         short year;
         byte mouth;
         byte day;
         byte hour;
         byte minute;
         byte second;
         short miniSecond;
         double latitude;//维度
         double longitude;//经度
         int height;

         long beginHz;
         int step;
         double[] testData = new double[1023];
         */
    }

    /**
     * 保存字符串数据
     *
     * @param content
     * @param path
     * @param fileName
     * @throws IOException
     */
    public static void writeData(String content, String path, String fileName) throws IOException {
        File f = new File(path);
        if (!f.exists()) {
            f.mkdirs();
        }
        File file = new File(path + fileName);
        if (!file.exists()) {
            file.createNewFile();
        }
        FileOutputStream out = new FileOutputStream(file, true);
        out.write(content.getBytes());
        out.flush();
        out.close();
    }

    /**
     * 读取二进制数据
     *
     * @param path
     * @param fileName
     * @throws FileNotFoundException
     * @throws IOException
     * @throws Exception
     */
    public static  List<RecordDataEntity>  readBinData(String path, String fileName)
            throws FileNotFoundException, IOException, Exception {
        // 挨个读取
        RandomAccessFile in = new RandomAccessFile(path + fileName, "r");
        List<RecordDataEntity> list = new ArrayList<>();

        int len = (int) (in.length() / RecordDataEntity.RecordSize);
        for (long i = 0; i < len; i++) {
            in.seek(i * RecordDataEntity.RecordSize);
            RecordDataEntity emp = readEmp(in);
            list.add(emp);
            Log.e(TAG, "readBinData: " + emp.toString());
        }
        return list;
    }

    /**
     * @param in
     * @return
     * @throws Exception
     */
    private static RecordDataEntity readEmp(DataInput in) throws Exception {
        RecordDataEntity entity = new RecordDataEntity();
        entity.setCarCode(in.readShort());
        entity.setDeviceInfo(in.readByte());
        entity.setYear(in.readShort());
        entity.setMouth(in.readByte());
        entity.setDay(in.readByte());
        entity.setHour(in.readByte());
        entity.setMinute(in.readByte());
        entity.setSecond(in.readByte());
        entity.setMiniSecond(in.readShort());
        entity.setLongitude(in.readDouble());
        entity.setLatitude(in.readDouble());
        entity.setHeight(in.readInt());
        entity.setBeginHz(in.readLong());
        entity.setStep(in.readInt());
        entity.setHzPoint(in.readInt());
        double[] testData = new double[1023];
        for (int i = 0; i < 1023; i++) {
            testData[i] = in.readDouble();
        }
        entity.setTestData(testData);
        return entity;
    }

    /**
     * 根据给定路径获取该路径下的 文件完整路径
     *
     * @param path
     * @return
     */
    public static List<String> getPath_FileNameList(String path) {
        List<String> list = new ArrayList<>();
        File file = new File(path);
        if (!file.exists()) return null;
        if (file.isFile()) {
            list.add(file.getPath());
        }
        if (file.isDirectory()) {
            File[] flist = file.listFiles();
            for (File ff : flist) {
                list.add(ff.getPath());
            }
        }
        for (int i = 0; i < list.size(); i++) {
            Log.e(TAG, "getPath_FileNameList: " + list.get(i));
        }
        return list;
    }

    /**
     * 获取文件名称
     *
     * @param path
     * @return
     */
    public static List<String> getFileName(String path) {
        List<String> list = new ArrayList<>();
        File file = new File(path);
        if (!file.exists()) return null;
        if (file.isFile()) {
            list.add(file.getName());
        }
        if (file.isDirectory()) {
            File[] flist = file.listFiles();
            for (File ff : flist) {
                list.add(ff.getName());
            }
        }
        for (int i = 0; i < list.size(); i++) {
            Log.e(TAG, "getFileName: " + list.get(i));
        }
        return list;
    }

    public static final int SIZETYPE_B = 1;// 获取文件大小单位为B的double值
    public static final int SIZETYPE_KB = 2;// 获取文件大小单位为KB的double值
    public static final int SIZETYPE_MB = 3;// 获取文件大小单位为MB的double值
    public static final int SIZETYPE_GB = 4;// 获取文件大小单位为GB的double值

    /**
     * 获取文件指定文件的指定单位的大小
     *
     * @param filePath 文件路径
     * @param sizeType 获取大小的类型1为B、2为KB、3为MB、4为GB
     * @return double值的大小
     */
    public static double getFileOrFilesSize(String filePath, int sizeType) {
        File file = new File(filePath);
        long blockSize = 0;
        try {
            if (file.isDirectory()) {
                blockSize = getFileSizes(file);
            } else {
                blockSize = getFileSize(file);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("获取文件大小", "获取失败!");
        }
        return FormetFileSize(blockSize, sizeType);
    }

    /**
     * 调用此方法自动计算指定文件或指定文件夹的大小
     *
     * @param filePath 文件路径
     * @return 计算好的带B、KB、MB、GB的字符串
     */
    public static String getAutoFileOrFilesSize(String filePath) {
        File file = new File(filePath);
        long blockSize = 0;
        try {
            if (file.isDirectory()) {
                blockSize = getFileSizes(file);
            } else {
                blockSize = getFileSize(file);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("获取文件大小", "获取失败!");
        }
        return FormetFileSize(blockSize);
    }

    /**
     * 获取指定文件大小
     *
     * @param file
     * @return
     * @throws Exception
     */
    private static long getFileSize(File file) throws Exception {
        long size = 0;
        if (file.exists()) {
            FileInputStream fis = null;
            fis = new FileInputStream(file);
            size = fis.available();
        } else {
            file.createNewFile();
            Log.e("获取文件大小", "文件不存在!");
        }
        return size;
    }

    /**
     * 获取指定文件夹
     *
     * @param f
     * @return
     * @throws Exception
     */
    private static long getFileSizes(File f) throws Exception {
        long size = 0;
        File flist[] = f.listFiles();
        for (int i = 0; i < flist.length; i++) {
            if (flist[i].isDirectory()) {
                size = size + getFileSizes(flist[i]);
            } else {
                size = size + getFileSize(flist[i]);
            }
        }
        return size;
    }

    /**
     * 转换文件大小
     *
     * @param fileS
     * @return
     */
    private static String FormetFileSize(long fileS) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        String wrongSize = "0B";
        if (fileS == 0) {
            return wrongSize;
        }
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "KB";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "MB";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "GB";
        }
        return fileSizeString;
    }

    /**
     * 转换文件大小,指定转换的类型
     *
     * @param fileS
     * @param sizeType
     * @return
     */
    private static double FormetFileSize(long fileS, int sizeType) {
        DecimalFormat df = new DecimalFormat("#.00");
        double fileSizeLong = 0;
        switch (sizeType) {
            case SIZETYPE_B:
                fileSizeLong = Double.valueOf(df.format((double) fileS));
                break;
            case SIZETYPE_KB:
                fileSizeLong = Double.valueOf(df.format((double) fileS / 1024));
                break;
            case SIZETYPE_MB:
                fileSizeLong = Double.valueOf(df.format((double) fileS / 1048576));
                break;
            case SIZETYPE_GB:
                fileSizeLong = Double.valueOf(df
                        .format((double) fileS / 1073741824));
                break;
            default:
                break;
        }
        return fileSizeLong;
    }
}
